﻿using System;
using nRoute.Components.Composition;
using nRoute.Samples.OfficerXcel.Components;
using nRoute.Samples.OfficerXcel.Model;
using nRoute.Services;

namespace nRoute.Samples.OfficerXcel.Services.Runtime
{
    [MapService(typeof(IApplicationSettingsService), InitializationMode = InitializationMode.OnDemand,
        Lifetime = InstanceLifetime.Singleton)]
    public class ApplicationSettingsService
        : IApplicationSettingsService
    {
        private const string ADVANCED_SETTINGS_KEY = "AdvancedSettingsKey";
        private const string COMMON_SETTINGS_KEY = "CommonSettingsKey";
        private const string AUTHOR_INFO_KEY = "AuthorInfoKey";

        private AdvancedSettings _advancedSettings;
        private CommonSettings _commonSettings;
        private AuthorInfo _authorInfo;

        public ApplicationSettingsService()
        {
            LoadOrInitializeSettings();
        }

#region Implementation of IApplicationSettingsService

        public event EventHandler SettingsChanged;

        public AdvancedSettings AdvancedSettings
        {
            get { return _advancedSettings; }
        }

        public CommonSettings CommonSettings
        {
            get { return _commonSettings; }
        }

        public AuthorInfo AuthorInfo
        {
            get { return _authorInfo; }
        }

        public void SaveSettings()
        {
            IsolatedStore.SaveDataObject(this.AdvancedSettings, ADVANCED_SETTINGS_KEY);
            IsolatedStore.SaveDataObject(this.CommonSettings, COMMON_SETTINGS_KEY);
            IsolatedStore.SaveDataObject(this.AuthorInfo, AUTHOR_INFO_KEY);
            if (SettingsChanged != null) SettingsChanged(this, EventArgs.Empty);
        }

        public void RevertSettings()
        {
            LoadOrInitializeSettings();
            if (SettingsChanged != null) SettingsChanged(this, EventArgs.Empty);
        }

#endregion

#region Helpers

        private void LoadOrInitializeSettings()
        {
            var _cachedAdvancedSettings = IsolatedStore.LoadDataObject<AdvancedSettings>(ADVANCED_SETTINGS_KEY) ??
                                          new AdvancedSettings();
            _advancedSettings = _cachedAdvancedSettings;

            var _cachedCommonSettings = IsolatedStore.LoadDataObject<CommonSettings>(COMMON_SETTINGS_KEY) ??
                                        new CommonSettings();
            _commonSettings = _cachedCommonSettings;

            var _cachedAuthorInfo = IsolatedStore.LoadDataObject<AuthorInfo>(AUTHOR_INFO_KEY) ??
                                        new AuthorInfo();
            _authorInfo = _cachedAuthorInfo;
        }

#endregion

    }
}
